package evolution;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;

import evolution.File;
import evolution.ResourceException;


public class FileEditor
{
	List<Line> lines = new LinkedList<Line>();
	private final File file;

	class Line
	{
		public String text;

		Line(String text)
		{
			this.text = text;
		}
	}

	public FileEditor(File file) throws ResourceException
	{
		this.file = file;
		BufferedReader reader = new BufferedReader(file.getReader());
		while (true)
		{
			String line;
			try
			{
				line = reader.readLine();
			}
			catch (IOException e)
			{
				throw new ResourceException("Failed to read line at line number " + (lines.size() + 1), e);
			}
			if (line == null)
				break;
			lines.add(new Line(line));
		}
	}

	public void insertText(int lineNo, String text)
	{
		if (lineNo <= 0)
		{
			throw new IllegalArgumentException("Line number must be greater than or equal to 1");
		}
		Line line = lines.get(lineNo - 1);
		line.text = text + line.text;
	}

	public void save() throws ResourceException
	{
		PrintWriter w = new PrintWriter(file.getWriter());
		for (Line line : lines)
		{
			w.println(line.text);
		}
		w.close();
	}
}
